package com.fhz.shop.ui.cart;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fhz.shop.R;
import com.fhz.shop.base.BaseFragment;
import com.fhz.shop.callback.ApiResponse;
import com.fhz.shop.databinding.FragmentCartBinding;
import com.fhz.shop.entity.HUser;
import com.fhz.shop.entity.UserCart;
import com.fhz.shop.ui.login.ui.login.LoginActivity;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * 购物车
 */
@AndroidEntryPoint
public class CartFragment extends BaseFragment<CartViewModel, FragmentCartBinding> {


    private List<UserCart> mUserCartList;
    @Override
    protected void initData() {

        binding.shopCarRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mUserCartList = new ArrayList<>();
        CartFragmentRvItemAdapter cartFragmentRvItemAdapter = new CartFragmentRvItemAdapter(getActivity(),mUserCartList);

        binding.shopCarRecyclerView.setAdapter(cartFragmentRvItemAdapter);
        cartFragmentRvItemAdapter.setOnItemClickListener((view, position) -> {

        });

        MMKV mmkv = MMKV.defaultMMKV();
        HUser user = mmkv.decodeParcelable("user", HUser.class);
        if(user == null){
            LoginActivity.launch(getActivity());
            return;
        }
        viewModel.getCartList(user.getUserId()).observe(this, new Observer<ApiResponse<List<UserCart>>>() {
            @Override
            public void onChanged(ApiResponse<List<UserCart>> listApiResponse) {
                mUserCartList.addAll(listApiResponse.getData());
                cartFragmentRvItemAdapter.notifyDataSetChanged();
                sumTotalPrice();
            }
        });

        //子View 点击事件
        cartFragmentRvItemAdapter.setOnSubItemClickListener((id, position) -> {
            if(id == R.id.goods_item_add){
                UserCart userCart = mUserCartList.get(position);
                System.out.println(userCart.getCarNum());
                viewModel.updateNum(userCart.getCarId(),1).observe(this, new Observer<ApiResponse<UserCart>>() {
                    @Override
                    public void onChanged(ApiResponse<UserCart> userCartApiResponse) {
                        userCartApiResponse.getData().setCheck(userCart.isCheck());
                        mUserCartList.set(position,userCartApiResponse.getData());
                        System.out.println(userCartApiResponse.getData().getCarTitle());
//                        cartFragmentRvItemAdapter.notifyDataSetChanged();
                        //rv使用局部刷新,提高效率,防止图片闪烁.
                        cartFragmentRvItemAdapter.notifyItemChanged(position,userCartApiResponse.getData().getCarNum());
                        sumTotalPrice();
                    }
                });
            }else if(id == R.id.goods_item_minus){
                UserCart userCart = mUserCartList.get(position);
                System.out.println(userCart.getCarNum());
                if(userCart.getCarNum() <= 1){
                    Toast.makeText(getActivity(), "不能在少了", Toast.LENGTH_SHORT).show();
                    return;
                }
                viewModel.updateNum(userCart.getCarId(),-1).observe(this, new Observer<ApiResponse<UserCart>>() {
                    @Override
                    public void onChanged(ApiResponse<UserCart> userCartApiResponse) {
                        userCartApiResponse.getData().setCheck(userCart.isCheck());
                        mUserCartList.set(position,userCartApiResponse.getData());

//                        cartFragmentRvItemAdapter.notifyDataSetChanged();
                        //rv使用局部刷新,提高效率,防止图片闪烁.
                        cartFragmentRvItemAdapter.notifyItemChanged(position,userCartApiResponse.getData().getCarNum());
                        sumTotalPrice();
                    }
                });
            } else if (id == R.id.goods_item_radio) {
                //状态改变监听
                sumTotalPrice();
            }
        });


        //编辑按钮点击事件
        binding.shopCarEdit.setOnClickListener( v -> {
            for (int i = 0; i < mUserCartList.size(); i++) {
                cartFragmentRvItemAdapter.notifyItemChanged(i,true);
            }
        });



    }

    /**
     * 计算总价
     */
    private void sumTotalPrice() {
        //更新总价
        int sum = 0;
        for (UserCart cart : mUserCartList) {
            //如果当前行不是被选中,不能算
            if(!cart.isCheck()){
//                return;
//                break;
                continue;//懂了吗?
            }
            sum += cart.getCarPrice() * cart.getCarNum();
        }
        binding.shopCarTotalPrice.setText(String.valueOf(sum));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_cart;
    }

    @Override
    protected CartViewModel createViewModel() {
        return viewModel = new ViewModelProvider(this).get(CartViewModel.class);
    }
}